# coding:UTF-8

import hashlib
import time

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect

from account.models import UserInfo as UserInfoDb, Message as MessageDb
from home.models import BlogInfo as BlogInfoDb
from controller.typechanging import NAME_TO_TYPE


def index(request):
    # GET
    obj = {}
    # 进入register
    if request.GET.get('status') == 'login':
        return HttpResponseRedirect('/account/register/')
    # 进入login
    else:
        return HttpResponseRedirect('/account/login/')


def save_session(request, user):
    request.session['email'] = user.email
    request.session['user_id'] = user.id
    request.session['status'] = 'login'
    request.session['username'] = user.username
    request.session['login_token'] = user.login_token
    request.session['head_img_url'] = user.head_img_url


def login_view(request):
    # GET
    if request.method == 'GET':
        web_type = {
            'type': '登录',
            'input_type': 'button',
            'status': 'login',
            'todo': 'register',
            'todotip': '还没有账号！！！'
        }
        return render_to_response(
            "account/loginorregister.html",
            {
                'web_type': web_type
            },
            context_instance=RequestContext(request)
        )

    # POST
    else:
        if request.POST.get('input_status') == 'login':
            email = request.POST.get('email', '')
            password = request.POST.get('password', '')
            password = hashlib.md5(password).hexdigest()
            # 用户未注册
            try:
                user = UserInfoDb.objects.get(email=email, password=password)
            except UserInfoDb.DoesNotExist:
                return HttpResponse("user is not exist!")

            # 保存用户信息进入session
            if user.password == password:
                now_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
                user.login_token = hashlib.md5(now_time).hexdigest()
                save_session(request, user)
                user.save(update_fields=("login_token",))
                return HttpResponseRedirect('/my_blog/?user=' + str(user.pk))
            else:
                return HttpResponseRedirect('/account/login/')

        else:
            return HttpResponse('/account/register/')


def register_view(request):
    # GET
    if request.method == 'GET':
        web_type = {
            'type': '注册',
            'input_type': 'hidden',
            'status': 'register_view',
            'todo': 'login',
            'todotip': '已经有账号！！！'
        }

        return render_to_response(
            "account/loginorregister.html",
            {
                'web_type': web_type
            },
            context_instance=RequestContext(request)
        )

    # POST
    else:
        email = request.POST.get('email', None)
        password = request.POST.get('password', None)
        # 该邮箱被注册了
        try:
            UserInfoDb.objects.get(email=email)
            return HttpResponse("email has been registered!")
        # 该邮箱未被注册
        except UserInfoDb.DoesNotExist:
            user = UserInfoDb()
            user.email = email
            user.password = hashlib.md5(password).hexdigest()
            now_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
            user.login_token = hashlib.md5(now_time).hexdigest()
            user.save()
            save_session(request, user)
            return HttpResponseRedirect('/home')


def logout_view(request):
    if request.session.get('status'):
        del request.session['status']
        del request.session['user_id']
        del request.session['email']
        del request.session['username']
        del request.session['login_token']
        del request.session['head_img_url']
    return HttpResponseRedirect('/home')


def backstage(request):
    # Redis Test
    # from controller.settings import read_from_cache
    # try:
    #     online_user_list = read_from_cache("online_user_list")
    # except Exception:
    #     online_user_list = []
    # print online_user_list

    obj = {}
    if (request.method == 'GET') and request.session.get("status"):
        obj['login'] = True
        obj['session'] = request.session
        blog_id = request.GET.get("blog_id", 0)

        # 后台重编辑操作
        if request.GET.get("type", "") == "editor":
            obj['tip'] = "editor"
            type_dict = NAME_TO_TYPE.values()
            obj["typeDict"] = type_dict
            try:
                blog = BlogInfoDb.objects.get(id=blog_id, status="True")
                obj["blog"] = blog
            except BlogInfoDb.DoesNotExist:
                return HttpResponse("原文已删除或未创建！")

            return render_to_response(
                "myblogs/rewriteblog.html",
                {
                    'obj': obj
                },
                context_instance=RequestContext(request)
            )

        # 后台置顶操作
        if request.GET.get("type", "") == "set_top":
            obj['tip'] = "set_top"
            # todo 此处缺乏置顶算法
            #
            #
            #

        # 后台删除操作
        if request.GET.get("type", "") == "delete":
            obj['tip'] = "delete"
            try:
                blog = BlogInfoDb.objects.get(id=blog_id, status="True")
                blog.status = "False"
                blog.save(update_fields=("status",))
            except BlogInfoDb.DoesNotExist:
                return HttpResponse("无法删除，文章可能不存在！")

        # 获取后台数据
        user_id = request.session.get('user_id', 1)
        try:
            blog_list = BlogInfoDb.objects.filter(blog_author_id=user_id, status="True").order_by('-createTime')
            obj['blog_list'] = blog_list
            new_msg_list = MessageDb.objects.filter(status="True").order_by('-createTime')
            obj['new_msg_list'] = list(new_msg_list)
            new_msg_list.update(status="False")
        except MessageDb.DoesNotExist:
            return HttpResponse("数据库操作失败！")

        return render_to_response(
            "account/backstage.html",
            {
                "obj": obj,
                "blog_author_id": request.session.get("user_id")
            },
            context_instance=RequestContext(request)
        )
    else:
        return HttpResponse("无权进行此操作！")


def get_all_message(request):
    if request.session.get("status") == "login":
        all_msg = MessageDb.objects.all().order_by('-createTime')

        return render_to_response(
            "account/allmessage.html",
            {
                "obj": {
                    'all_msg': all_msg
                }
            },
            context_instance=RequestContext(request)
        )
    else:
        return HttpResponse("无权进行此操作！")


def login(request, user_id):
    return HttpResponse(user_id)
